import { useState, useEffect } from 'react'
import { Task } from '../types'
import TaskItem from './TaskItem'
import SwipeableTaskItem from './SwipeableTaskItem'

interface TaskSectionProps {
  title: string
  tasks: Task[]
  onToggleComplete: (taskId: string) => void
  onTaskClick: (taskId: string) => void
  onDeleteTask?: (taskId: string) => void
}

export default function TaskSection({ title, tasks, onToggleComplete, onTaskClick, onDeleteTask }: TaskSectionProps) {
  const [isMobile, setIsMobile] = useState(false)

  // 检测移动端环境
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth < 768)
    }
    
    checkIsMobile()
    window.addEventListener('resize', checkIsMobile)
    return () => window.removeEventListener('resize', checkIsMobile)
  }, [])

  if (tasks.length === 0) return null

  return (
    <div className="mb-6">
      {/* 分组标题 - 响应式设计 */}
      <div className="px-3 sm:px-4 py-3 mb-3">
        <div className="flex items-center gap-2 sm:gap-3">
          <div className="w-1 h-5 sm:h-6 bg-gradient-to-b from-blue-500 to-blue-600 rounded-full"></div>
          <h2 className="text-base sm:text-lg font-bold text-theme-text">
            {title}
          </h2>
          <span className="px-2 sm:px-2.5 py-0.5 sm:py-1 bg-blue-50 text-blue-700 text-xs rounded-full font-semibold border border-blue-100">
            {tasks.length}
          </span>
        </div>
      </div>

      {/* 任务列表 - 响应式网格布局 */}
      <div className="px-3 sm:px-4 lg:px-6 xl:px-8">
        <div className={`${
          isMobile 
            ? 'space-y-3' // 移动端单列垂直布局
            : 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 lg:gap-4' // 桌面端网格布局
        }`}>
          {tasks.map((task, index) => (
            <div
              key={task.id}
              className="animate-fade-in-up"
              style={{ animationDelay: `${index * 0.03}s` }}
            >
              {isMobile && onDeleteTask ? (
                // 移动端使用可滑动组件
                <SwipeableTaskItem
                  task={task}
                  onToggleComplete={onToggleComplete}
                  onTaskClick={onTaskClick}
                  onDeleteTask={onDeleteTask}
                />
              ) : (
                // 桌面端使用普通组件
                <TaskItem
                  task={task}
                  onToggleComplete={onToggleComplete}
                  onClick={onTaskClick}
                />
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}